package com.boot.down.util.redis;

import redis.clients.jedis.Jedis;

import static com.boot.down.util.redis.LockConstants.*;


/**
 * 加锁与解锁(释放锁) 测试四(利用lua脚本处理 相同 for的情况) (具有原子性的释放锁)
 * @author dell
 */
public class LockCase4 extends RedisLock {


	public LockCase4(Jedis jedis, String lockKey) {
		super(jedis, lockKey);
	}

	@Override
	public void lock() {
		while (true) {
			//设置锁的过期时间
			String result = jedis.set(lockKey, lockValue, NOT_EXIST, SECONDS,30);
			if (OK.equals(result)) {
				System.out.println(Thread.currentThread().getId() + "加锁成功!");
				break;
			}
		}
	}

	@Override
	public void unlock() {
		// 使用lua脚本进行原子删除操作
		String checkAndDelScript = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
				"return redis.call('del', KEYS[1]) " +
				"else " +
				"return 0 " +
				"end";
		jedis.eval(checkAndDelScript, 1, lockKey, lockValue);
	}
}
